package zhr.chapter10;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Example10_4 {
    public static void main(String[] args) {
        File helloFile=new File("d://","HelloWorld.txt");
        //创建文件
        boolean isCreated= false;
        try {
            isCreated = helloFile.createNewFile();
            if(isCreated||helloFile.exists()){
                //以字符流方式写入文件heeloFile
                String content[]={
                        "咏柳",
                        "朝代：唐朝",
                        "作者：贺知章"
                };
                RandomAccessFile fileRandom =new RandomAccessFile(helloFile,"rw");
                for(String str:content){
                    byte[] contentBytes=str.getBytes("gb2312");
                    fileRandom.write(contentBytes);
                    fileRandom.writeChars(System.getProperty("line.separator"));
                }
                fileRandom.close();
                fileRandom=new RandomAccessFile(helloFile,"rw");
                String str="碧玉妆成一树高,万条垂下绿丝绦,不知细叶谁裁出,二月春风似剪刀.";
                long position=fileRandom.length();
                fileRandom.seek(position);
                fileRandom.write(str.getBytes("gb2312"));
                position=0;
                while (position<fileRandom.length()){
                    str=fileRandom.readLine();
                    position=fileRandom.getFilePointer();
                    byte[] strBytes=str.getBytes("ISO-8859-1");
                    System.out.println(new String(strBytes));
                }
                fileRandom.close();
            }
        } catch (IOException e) {
            Logger.getLogger(Example10_4.class.getName()).log(Level.SEVERE,null,e);
        }

    }
}
